package com.example.order.controller;

import com.example.order.config.AppFinal;
import com.example.order.model.UserInfo;
import com.example.order.service.UserInfoService;
import com.example.order.tools.ResponseBody;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 注册功能
     * @return
     */
    @RequestMapping("reg")
    public ResponseBody reg(UserInfo userInfo){
        int data = userInfoService.reg(userInfo);
        return new ResponseBody(0,"",data);
    }

    /**
     * 登录功能
     * @param userInfo
     * @return
     */
    @RequestMapping("/login")
    public ResponseBody login(UserInfo userInfo , HttpServletRequest request){
        UserInfo data = userInfoService.login(userInfo);
        if(data != null && data.getId() > 0){
            HttpSession session = request.getSession();
            session.setAttribute(AppFinal.USERINFO_SESSION_KEY,data);
        }
        return new ResponseBody(0 , "" , data);
    }

    /**
     * 判断当前是否为登录状态
     * @return
     */
    @RequestMapping("/islogin")
    public ResponseBody isLogin(HttpServletRequest request){
        UserInfo userInfo = null;
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppFinal.USERINFO_SESSION_KEY) != null){
            userInfo = (UserInfo) session.getAttribute(AppFinal.USERINFO_SESSION_KEY);
        }
        return new ResponseBody(0 , "" , userInfo);
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping("/logout")
    public ResponseBody logout(HttpServletRequest request){
        int data = 0;
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppFinal.USERINFO_SESSION_KEY) != null){
            session.removeAttribute(AppFinal.USERINFO_SESSION_KEY);
            data = 1;
        }
        return new ResponseBody(0 , "" , data);
    }
}
